# Copyright (c) 2025 Songwufeng
# [Software Name] is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#          http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import subprocess
import os
import sys
import logging
import ctypes

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 定义 Windows API 相关常量和函数
PROCESS_ALL_ACCESS = 0x1F0FFF
TH32CS_SNAPPROCESS = 0x00000002
CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot
Process32First = ctypes.windll.kernel32.Process32First
Process32Next = ctypes.windll.kernel32.Process32Next
OpenProcess = ctypes.windll.kernel32.OpenProcess
TerminateProcess = ctypes.windll.kernel32.TerminateProcess
CloseHandle = ctypes.windll.kernel32.CloseHandle


class PROCESSENTRY32(ctypes.Structure):
    _fields_ = [("dwSize", ctypes.c_ulong),
                ("cntUsage", ctypes.c_ulong),
                ("th32ProcessID", ctypes.c_ulong),
                ("th32DefaultHeapID", ctypes.POINTER(ctypes.c_ulong)),
                ("th32ModuleID", ctypes.c_ulong),
                ("cntThreads", ctypes.c_ulong),
                ("th32ParentProcessID", ctypes.c_ulong),
                ("pcPriClassBase", ctypes.c_long),
                ("dwFlags", ctypes.c_ulong),
                ("szExeFile", ctypes.c_char * 260)]


def get_script_paths():
    """
    获取 script1.py 和 script2.py 的文件路径
    """
    current_dir = os.path.dirname(os.path.abspath(__file__))
    script1_path = os.path.join(current_dir, 'detection', 'screenshot.py')
    script2_path = os.path.join(current_dir, 'detection', 'logihub.py')
    return script1_path, script2_path


def run_hidden(script_path):
    """
    以隐藏窗口的方式异步启动 Python 脚本，并尽量隐藏进程
    """
    startupinfo = None
    if sys.platform.startswith('win'):
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = subprocess.SW_HIDE
    try:
        process = subprocess.Popen(['python', script_path], startupinfo=startupinfo)
        logging.info(f"成功启动脚本: {script_path}")
        # 这里可以添加更复杂的隐藏进程逻辑，比如修改进程的可见性属性等
        return process
    except FileNotFoundError:
        logging.error("Python 解释器未找到，请确保 Python 已正确安装并配置到系统环境变量中。")
        return None
    except Exception as e:
        logging.error(f"启动脚本 {script_path} 时发生其他错误: {e}")
        return None


def main():
    """
    主函数，负责启动两个脚本并等待它们执行完毕
    """
    script1_path, script2_path = get_script_paths()
    logging.info(f"正在启动 {script1_path} 和 {script2_path}")

    process1 = run_hidden(script1_path)
    process2 = run_hidden(script2_path)

    if process1 and process2:
        logging.info(f"{script1_path} 和 {script2_path} 已成功启动")
        try:
            # 等待两个进程执行完毕
            process1.wait()
            process2.wait()
            logging.info(f"{script1_path} 和 {script2_path} 执行完毕")
        except Exception as e:
            logging.error(f"等待进程执行时发生错误: {e}")
    else:
        logging.error("启动脚本时出现问题")


if __name__ == "__main__":
    main()